package com.zhiqian.community.service;

import com.zhiqian.community.entity.LoginTicket;
import com.zhiqian.community.entity.User;
import com.zhiqian.community.util.CommunityUtil;
import com.zhiqian.community.util.MailClient;
import com.zhiqian.community.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LoginService{
    @Autowired
    private UserService userService;

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private RedisTemplate redisTemplate;



    public Map<String, Object> login(User user, int expiredSeconds) {
        Map<String, Object> map = loginParamCheckout(user);
        if (map.isEmpty()) {
            //校验通过，生成登陆凭证
            String ticket=CommunityUtil.generateUUID();
            String ticketUserKey = RedisKeyUtil.getTicketUserKey(ticket);
            user = userService.getUserById(user.getId());
            redisTemplate.opsForValue().set(ticketUserKey,user,expiredSeconds, TimeUnit.SECONDS);
            map.put("ticket",ticket);
        }
        return map;
    }

    public void logout(String ticket){
        String ticketUserKey = RedisKeyUtil.getTicketUserKey(ticket);
        redisTemplate.delete(ticketUserKey);
    }

    /**
     * 生成并发送忘记密码功能的验证码
     * @param email
     * @return
     */
    public Map<String,Object> sendAuthCode(String email){
        Map<String, Object> map = emailCheckout(email);
        if (map.isEmpty()){
            //生成验证码
            String authCode = CommunityUtil.generateUUID().substring(0,10);
            sendAuthCodeEmail(email,authCode);
            map.put("authCode",authCode);
        }
        return map;
    }


    private Map<String, Object> emailCheckout(String email){
        Map<String,Object> map=new HashMap<>();
        if (StringUtils.isBlank(email)){
            map.put("errMsg","邮箱不能为空");
            return map;
        }
        User user = userService.getUserByEmail(email);
        if (user==null){
            map.put("errMsg","该邮箱对应的账号不存在");
            return map;
        }
        if (user.getStatus()==0){
            map.put("errMsg","该邮箱对应的账号未激活");
            return map;
        }
        return map;
    }

    private void sendAuthCodeEmail(String email,String authCode){
        Context context = new Context();
        context.setVariable("authCode",authCode);
        context.setVariable("email",email);
        String content = templateEngine.process("/mail/forget", context);
        mailClient.sendMail(email,"找回密码",content);
    }

    private Map<String, Object> loginParamCheckout(User user) {
        Map<String, Object> map = new HashMap<>();
        if (user == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        if (StringUtils.isBlank(user.getUsername())) {
            map.put("usernameMsg", "请输入用户名");
            return map;
        }
        if (StringUtils.isBlank(user.getPassword())) {
            map.put("passwordMsg", "请输入密码");
            return map;
        }
        User userByName = userService.getUserByName(user.getUsername());
        if (userByName == null || !userByName.getPassword().equals(CommunityUtil.MD5(user.getPassword()+ userByName.getSalt()))) {
            map.put("errMsg", "账号或密码输入有误!");
            return map;
        }
        if (userByName.getStatus() == 0) {
            map.put("errMsg", "该账号未激活");
            return map;
        }
        user.setId(userByName.getId());
        return map;
    }

    private LoginTicket createLoginTicket(Integer userId, int expiredSeconds) {
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(userId);
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setStatus(0);
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds*1000));
        return loginTicket;
    }

}
